<template>
  <div class="mb-6 flex items-center bg-white px-4 py-3 rounded-lg shadow-sm">
    <template v-for="(item, index) in breadcrumbItems" :key="index">
      <!-- 分隔箭头 -->
      <template v-if="index > 0">
        <i class="fas fa-chevron-right text-gray-300 mx-2 text-xs"></i>
      </template>

      <!-- 最后一级，高亮显示 -->
      <template v-if="index === breadcrumbItems.length - 1">
        <span class="text-blue-500 font-medium">{{ item.name }}</span>
      </template>

      <!-- 其它级别，可点击跳转 -->
      <template v-else>
        <router-link
          :to="item.path"
          class="text-gray-500 hover:text-blue-500 transition-colors duration-200 font-medium"
        >
          <!-- 首项显示 Home 图标 -->
          <i v-if="index === 0" class="fas fa-home text-gray-400 mr-2"></i>
          {{ item.name }}
        </router-link>
      </template>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue';
import { useRoute } from 'vue-router';

interface Crumb {
  path: string;
  name: string;
}

const route = useRoute();

const breadcrumbItems = computed<Crumb[]>(() => {
  const crumbs: Crumb[] = [];
  let accPath = '';

  // 遍历所有匹配的路由记录，从根到当前
  for (const record of route.matched) {
    // 如果路由有重定向，使用重定向的路径
    const path = record.redirect || record.path;
    // 如果是绝对路径，直接使用；否则拼接到当前路径
    accPath = path.startsWith('/') ? path : `${accPath}/${path}`.replace(/\/+/g, '/');
    // 确保路径不以多个斜杠开头
    accPath = accPath.replace(/^\/+/, '/');


    crumbs.push({
      path: accPath,
      // 优先读取 meta.breadcrumb，否则 fallback 到 record.name
      name: (record.meta.breadcrumb as string) ||
            (record.meta.title as string) ||  // 有些示例用 meta.title :contentReference[oaicite:2]{index=2}
            (record.name as string) || ''
    });
  }

  return crumbs;
});
</script>
